import 'dart:async';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
import 'package:flutter/rendering.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:my_flutter_app/image_and_icon_test.dart';
import 'package:my_flutter_app/textfield_and_form.dart';
import 'animated_switcher_test.dart';
import 'animated_widget_test.dart';
import 'button_test.dart';

import 'caculate/caculate_page.dart';
import 'common.dart';
import 'container_test.dart';
import 'custom_component_test.dart';
import 'custom_ui_framework_test.dart';
import 'file_operation_test.dart';
import 'functional_widget_test.dart';
import 'http_web_test.dart';
import 'image_internal_test.dart';
import 'l10n/localization_intl.dart';
import 'local_language_test.dart';
import 'native_plugin_test.dart';
import 'platform_view_test.dart';
import 'progressindicator_test.dart';
import 'scrollable_widget_test.dart';
import 'switch_and_checkbox_test.dart';
import 'texture_camera_test.dart';
import 'widget_state_manage.dart';

void main() async {
  cameras = await availableCameras();
  runApp(MyApp());
  PaintingBinding.instance.imageCache.maximumSize = 2000;
  PaintingBinding.instance.imageCache.maximumSizeBytes = 200 << 20;
}

typedef bool CALLBACK();

final MY_TAG = "=========";
final MY_TAG_1 = "===+++===";

// TargetPlatform debugDefaultTargetPlatformOverride=TargetPlatform.iOS;

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    /*
    MaterialApp(
      onGenerateTitle: (context) { return DemoLocalizations.of(context).title;},
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,

        DemoLocalizationsDelegate(),
      ],
    );
    */

    Locale _locale;

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      // 多语言app标题
      onGenerateTitle: (context) {
        if(Localizations.localeOf(context).languageCode == 'en') {
          _locale =  Locale('en', 'US');
        }
        return DemoLocalizations.of(context).title;
      },
      initialRoute: 'home',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),

      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        DemoLocalizationsDelegate(),
      ],
      supportedLocales: [
        const Locale('en', 'US'),
        const Locale('zh', 'CN'),
      ],
//      localeListResolutionCallback: (List<Locale> locals, Iterable<Locale> supportedLocales) {
//        print(MY_TAG_1 + "locale= " + _locale.toString());
//        return _locale;
//      },
      routes: {
        'new_page': (context) => NewRoute(),
        'home': (context) => MyHomePage(title: 'Flutter Demo Home Page'),
        'echo_rout': (context) => EchoRout(),
        'tip': (context) =>
            TipRoute(text: ModalRoute.of(context).settings.arguments),
        'tip1': (context) {
          return TipRoute(text: ModalRoute.of(context).settings.arguments);
        },
        'counter_rout': (context) => CounterRout(),
        'fatherstatefulwidgetstaterout': (context) =>
            FatherStatefulWidgetStateRout(),
      },
      //home: MyHomePage(title: 'Flutter Demo Home Page'),
      onGenerateRoute: (RouteSettings settings) {
        return MaterialPageRoute(builder: (context) {
          String routeName = settings.name;
          if (routeName != null) {
          } else {}
          return null;
        });
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        // title: Text(widget.title),
        title: Text(DemoLocalizations.of(context).title),
      ),
      body: SingleChildScrollView(
        child: Center(
          // Center is a layout widget. It takes a single child and positions it
          // in the middle of the parent.
          child: Column(
            // Column is also a layout widget. It takes a list of children and
            // arranges them vertically. By default, it sizes itself to fit its
            // children horizontally, and tries to be as tall as its parent.
            //
            // Invoke "debug painting" (press "p" in the console, choose the
            // "Toggle Debug Paint" action from the Flutter Inspector in Android
            // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
            // to see the wireframe for each widget.
            //
            // Column has various properties to control how it sizes itself and
            // how it positions its children. Here we use mainAxisAlignment to
            // center the children vertically; the main axis here is the vertical
            // axis because Columns are vertical (the cross axis would be
            // horizontal).
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'You have pushed the button this many times:',
              ),
              Text(
                '$_counter',
                style: Theme.of(context).textTheme.display1,
              ),
              Text(say("Android", "create a world", "Android phone")),
              Text(test1()),
              FlatButton(
                child: Text("jump to new Route"),
                textColor: Colors.blue,
                onPressed: () {
                  // Navigator.pushNamed(context, "new_page");
                  Navigator.of(context)
                      .pushNamed('echo_rout', arguments: 'hi Echo_Rout');
                },
              ),
              FlatButton(
                child: Text("jump to RouterTestTip"),
                textColor: Colors.blue,
                onPressed: () {
                  // Navigator.pushNamed(context, "new_page");
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) {
                            return RouterTestTip();
                          },
                          settings: RouteSettings(
                              name: 'setting',
                              isInitialRoute: false,
                              arguments: 12),
                          maintainState: true,
                          fullscreenDialog: false));
                },
              ),
              RandomWordsWidget(),
              FlatButton(
                child: Text('debugDumpApp()'),
                onPressed: () {
                  // debugDumpApp();
                  // debugDumpRenderTree();
                  // debugDumpLayerTree();
                  // debugDumpSemanticsTree();
                },
              ),
              FlatButton(
                child: Text("jump to CounterRout"),
                onPressed: () {
                  Navigator.pushNamed(context, "counter_rout");
                },
              ),
              RaisedButton(
                onPressed: () {
                  Navigator.pushNamed(context, "fatherstatefulwidgetstaterout");
                },
                child: Text("jump to fatherstatefulwidget"),
              ),
              RaisedButton(
                child: Text("CupertinoTestRoute"),
                onPressed: () {
                  Navigator.push(context,
                      CupertinoPageRoute(builder: (context) {
                    return CupertinoTestRoute();
                  }));
                },
              ),
              RaisedButton(
                child: Text("TapBox"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return TapBox();
                  }));
                },
              ),
              RaisedButton(
                child: Text("ButtonTest"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return ButtonRoute();
                  }));
                },
              ),
              RaisedButton(
                child: Text("ImageAndIcon"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return ImageAndIconRoute();
                  }));
                },
              ),
              RaisedButton(
                child: Text("SwitchAndCheckBoxTestRoute"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return SwitchAndCheckBoxTestRoute();
                  }));
                },
              ),
              RaisedButton(
                child: Text("TextAndField"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return TextFieldAndFormRoute();
                  }));
                },
              ),
              RaisedButton(
                child: Text("ProgressIndicator"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return ProgressIndicatorTestRoute();
                  }));
                },
              ),
              RaisedButton(
                child: Text("ContainerTestRoute"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return ContainerTestRoute();
                  }));
                },
              ),
              RaisedButton(
                child: Text("ScrollableWidgetTestRoute"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return ScrollableWidgetTestRoute();
                  }));
                },
              ),
              RaisedButton(
                child: Text("FunctionalWidgetTestIndexRote"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return FunctionalWidgetTestIndexRote();
                  }));
                },
              ),
              RaisedButton(
                child: Text("AnimatedWidgetTestIndexRote"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return AnimatedWidgetTestIndexRote();
                  }));
                },
              ),
              RaisedButton(
                child: Text("AnimatedSwitcherTestIndexRoute"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return AnimatedSwitcherTestIndexRoute();
                  }));
                },
              ),

              RaisedButton(
                child: Text("CustomComponentTestIndexRote"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return CustomComponentTestIndexRote();
                  }));
                },
              ),
              RaisedButton(
                child: Text("FileOperationTestRoute"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return FileOperationTestRoute();
                  }));
                },
              ),
              RaisedButton(
                child: Text("HttpWebTestIndexRote"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return HttpWebTestIndexRote();
                  }));
                },
              ),
              RaisedButton(
                child: Text("BatteryPluginTest"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return BatteryPluginTest();
                  }));
                },
              ),
              RaisedButton(
                child: Text("TextureCameraTextRoute"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return TextureCameraTextRoute();
                  }));
                },
              ),
              RaisedButton(
                child: Text("PlatformViewTestRoute"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return PlatformViewTestRoute();
                  }));
                },
              ),
              RaisedButton(
                child: Text("LocalLanguageTestRoute"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return LocalLanguageTestRoute();
                  }));
                },
              ),
              RaisedButton(
                child: Text("ImageInternalTestRoute"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return ImageInternalTestRoute();
                  }));
                },
              ),
              RaisedButton(
                child: Text("CustomHome"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return CustomHome();
                  }));
                },
              ),
              RaisedButton(
                child: Text("CalculatorPage"),
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return CalculatorPage();
                  }));
                },
              ),

            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),

      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  String test() {
    var testMsg = "msg";
    dynamic t;
    Object x;
    t = 'hi world';
    x = 'hello Object';

    t = 1000;
    x = 1000;

    return testMsg;
  }

  dynamic a;
  Object b;

  String test1() {
    var testMsg = "msg";
    a = "sfdfsdfdsfsdfdsa";
    b = "";
    printLengths();

    final str = 'hi world';
    print('$MY_TAG$str');
    const str1 = 'hello world';
    print('$MY_TAG$str1');

    // testNoble(false);
    // _nobleGases[0] = 10;
    print('$MY_TAG $isNoble(1)');

    print('$MY_TAG $isNoble1(1)');

    var say = (str) {
      print(str);
    };
    say("$MY_TAG say hello");

    void execute(var callback) {
      callback();
    }

    execute(() => print("$MY_TAG callback......."));
    enableFlags(bold: true, hidden: false);

    //testFuture();
    //testAsync();
    testStream();

//    FlutterError.onError = (FlutterErrorDetails details) {
//      reportErrorAndLog(details);
//    };
//
//    runZoned(
//      () => runApp(MyApp()),
//      zoneSpecification: ZoneSpecification(
//        print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
//          collectLog(line);
//        },
//      ),
//      onError: (Object obj, StackTrace stack) {
//        var details = makeDetails(obj, stack);
//        reportErrorAndLog(details);
//      },
//    );

    var future = new Future.value(499);
    runZoned(() {
      var future2 = future.then((_) {
        throw "error in first error-zone";
      });
      runZoned(() {
        var future3 = future2.catchError((e) {
          print("Never reached!");
        });
      }, onError: (e) {
        print("unused error handler");
      });
    }, onError: (e) {
      print("catches error of first error-zone.");
    });

    return testMsg;
  }

  void collectLog(String line) {
    // 搜集日志
    print(MY_TAG + "搜集日志");
  }

  void reportErrorAndLog(FlutterErrorDetails details) {
    // 上报错误和日志逻辑
    print(MY_TAG + "上报错误和日志逻辑");
  }

  FlutterErrorDetails makeDetails(Object obj, StackTrace stack) {
    // 构建错误信息
    print(MY_TAG + "构建错误信息");
    return new FlutterErrorDetails(exception: obj, stack: stack);
  }

  printLengths() {
    print('$MY_TAG${a.length}');
    // print(b.length);
  }

  var _nobleGases;

  bool isNoble(int atomicNumber) {
    return _nobleGases[atomicNumber] != null;
  }

  bool isNoble1(int atomicNumber) => _nobleGases[atomicNumber] != null;

  void testNoble(CALLBACK cb) {
    print(MY_TAG + '$cb()');
  }

  /// 可选的位置参数
  String say(String from, String msg, [String device]) {
    var result = '$from says $msg';
    if (device != null) result = '$result with a $device.';
    return result;
  }

  /// 可选命名参数
  void enableFlags({bool bold, bool hidden}) {
    print("$MY_TAG: bold = $bold, hidden = $hidden");
  }

  void testFuture() {
    Future.delayed(new Duration(seconds: 2), () {
      // return 'hi Future';
      throw AssertionError("Error");
    }).then((data) {
      print(MY_TAG + data);
    }).catchError((e) {
      print(MY_TAG + "error:" + e.message);
    }).whenComplete(() {
      print(MY_TAG + 'complete...');
    });

//    Future.delayed(new Duration(seconds: 2), (){
//      // return 'hi Future';
//      throw AssertionError("Error");
//    }).then((data) {
//      print(MY_TAG + data);
//    }, onError: (e){
//      print(e.message);
//    });

    Future.wait([
      Future.delayed(new Duration(seconds: 2), () {
        return 'hello';
      }),
      Future.delayed(new Duration(seconds: 4), () {
        return ' flutter';
      })
    ]).then((results) {
      print(MY_TAG + results[0] + results[1]);
    }).catchError((e) {
      print(MY_TAG + e.message);
    });
  }

  void testAsync() {
    Future<String> login(String username, String pwd) {
      return Future.delayed(new Duration(milliseconds: 500), () {
        print(MY_TAG + "login...");
        return username + pwd;
      });
    }

    Future<String> getUserInfo(String id) {
      return Future.delayed(new Duration(milliseconds: 500), () {
        print(MY_TAG + "getUserInfo...");
        return "userId + $id";
      });
    }

    Future saveUserInfo(String userInfo) {
      return Future.delayed(new Duration(seconds: 2), () {
        print(MY_TAG + "saveUserInfo...");
        return userInfo;
      }).then((data) {
        print(MY_TAG + "result:saveUserInfo: " + data);
      });
    }

    /*
    login("yuangudashen", "*******").then((id){
      getUserInfo(id).then((userInfo){
        saveUserInfo(userInfo).then((aa){
          print(MY_TAG + "aa = "+aa);
        });
      });
    });
    */

    /// 使用Future消除Callback Hell
//    login("yuangudashen", "*******").then((id){
//      return getUserInfo(id);
//    }).then((userInfo){
//      return saveUserInfo(userInfo);
//    }).then((e){
//      print(e);
//    }).catchError((e){
//      print(MY_TAG + e.message);
//    });

    /// 使用async/await消除callback Hell
    task() async {
      try {
        String id = await login("yuangudashen", "*******");
        String userInfo = await getUserInfo(id);
        await saveUserInfo(userInfo);
      } catch (e) {
        print(MY_TAG + e);
      }
    }

    task();
  }

  testStream() {
    Stream.fromFutures([
      Future.delayed(new Duration(seconds: 2), () {
        return 'hello flutter 1';
      }),
      Future.delayed(new Duration(seconds: 3), () {
        throw AssertionError('Error');
      }),
      Future.delayed(new Duration(seconds: 4), () {
        return 'hello flutter 2';
      })
    ]).listen((onData) {
      print(MY_TAG + onData);
    }, onError: (e) {
      print(MY_TAG + e.message);
    }, onDone: () {
      print(MY_TAG + "done.");
    });
  }
}

class NewRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text("I\'m a new Route"),
      ),
      body: Center(
        child: Text("I am a new Route Page"),
      ),
    );
  }
}

class TipRoute extends StatelessWidget {
  TipRoute({
    Key key,
    @required this.text,
  }) : super(key: key);

  final String text;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('提示'),
      ),
      body: Padding(
        padding: EdgeInsets.all(18),
        child: Center(
          child: Column(
            children: <Widget>[
              Text(text),
              RaisedButton(
                onPressed: () => Navigator.pop(context, '我是返回值'),
                child: Text('返回'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

class RouterTestTip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(
          onPressed: () async {
            var result = await Navigator.of(context)
                .pushNamed('tip1', arguments: '我是来自888888的提示');
//            var result = await Navigator.push(context,
//                MaterialPageRoute(builder: (context) {
//              return TipRoute(
//                text: '我是来自888888的提示',
//              );
//            }));
            print('路由返回值: $result');
          },
          child: Text('打开提示页')),
    );
  }
}

class EchoRout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var args = ModalRoute.of(context).settings.arguments;
    print(MY_TAG + args);
    return Center(
      child: Text('$args'),
    );
  }
}

class RandomWordsWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final wordPair = WordPair.random();
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Text(wordPair.toString()),
    );
  }
}

class CounterRout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CounterWidget();
    //return Text("xxxxxxxx");
  }
}

class CounterWidget extends StatefulWidget {
  const CounterWidget({Key key, this.initValue: 0});

  final int initValue;

  @override
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int _counter;

  @override
  void initState() {
    super.initState();
    _counter = widget.initValue;
    print(MY_TAG_1 + "initState");
  }

  @override
  Widget build(BuildContext context) {
    print(MY_TAG_1 + "build");
    return Scaffold(
      body: Center(
        child: FlatButton(
          child: Text("$_counter"),
          onPressed: () => setState(() => _counter++),
        ),
      ),
    );
  }

  @override
  void didUpdateWidget(CounterWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    print(MY_TAG_1 + "didUpdateWidget");
  }

  @override
  void deactivate() {
    super.deactivate();
    print(MY_TAG_1 + "deactivate");
  }

  @override
  void dispose() {
    super.dispose();
    print(MY_TAG_1 + "dispose");
  }

  @override
  void reassemble() {
    super.reassemble();
    print(MY_TAG_1 + "reassemble");
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print(MY_TAG_1 + "didChangeDependencies");
  }
}

class FatherStatefulWidgetStateRout extends StatefulWidget {
  @override
  _FatherStatefulWidgetStateRoutState createState() =>
      _FatherStatefulWidgetStateRoutState();
}

class _FatherStatefulWidgetStateRoutState extends State {
  static GlobalKey<ScaffoldState> _globalKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _globalKey,
      appBar: AppBar(
        title: Text("子树中获取State对象"),
      ),
      body: Center(
        child: Builder(builder: (context) {
          return RaisedButton(
            onPressed: () {
              ScaffoldState _state;
              // _state = context.ancestorStateOfType(TypeMatcher<ScaffoldState>());
              // _state = Scaffold.of(context);
              _state = _globalKey.currentState;
              _state.showSnackBar(
                SnackBar(content: Text("I am SnackBar")),
              );
            },
            child: Text("显示SnackBar"),
          );
        }),
      ),
    );
  }
}

class CupertinoTestRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: CupertinoNavigationBar(
        middle: Text("CupertinoTestRoute"),
      ),
      child: Center(
        child: CupertinoButton(
          color: CupertinoColors.activeBlue,
          child: Text("Press"),
          onPressed: () {},
        ),
      ),
    );
  }
}
